<template>
  <div class="login">
    <div class="login-content">
      <div class="title">登录</div>
      <VanForm @submit="onSubmit()">
        <VanCellGroup>
          <VanField
            v-model="account"
            type="account"
            placeholder="请输入账号"
            style="margin-bottom: 10px"
          />
          <VanField
            v-model="password"
            type="password"
            placeholder="请输入密码"
          />
        </VanCellGroup>
        <div style="margin: 10px">
          <VanButton
            block
            native-type="submit"
            color="rgb(219,193,95)"
            style="border-radius: 10px"
          >
            登录
          </VanButton>
        </div>
      </VanForm>
    </div>
  </div>
</template>
<script setup>
import { reactive, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { request } from "@/api/request";
import commonApi from "@/api/common.js";

import {
  Form as VanForm,
  Field as VanField,
  CellGroup as VanCellGroup,
  Button as VanButton,
  showToast,
} from "vant";
const router = useRouter();

const state = reactive({
  account: "13888888888",
  password: "123456",
});

onMounted(() => {
  localStorage.removeItem("userInfo");
});
const onSubmit = () => {
  const { account, password } = state;
  if (!account || !password) {
    showToast(`请输入${!userName ? "账号" : !password ? "密码" : ""}`);
    return;
  }
  // 登录
  request(commonApi.login, {
    data: { account, password },
  })
    .then((res) => {
      const {code, data} = res
      if (+code === 1 && data) {
        const { userinfo = {} } = data;
        const { token } = userinfo;
        showToast("登录成功");
        localStorage.setItem("h5-token", `${token}`);
        localStorage.setItem("userInfo", JSON.stringify(userinfo));
        router.replace("/home");
      } else {
        throw res;
      }
    })
    .catch((e) => {
      showToast(e.msg || (e.body && e.body.msg) || "登录失败，请稍后重试");
    });
};
const { account, password } = toRefs(state);
</script>
<style scoped lang="scss">
.login {
  font-family: PingFangSC, PingFang SC;
  background: #fff;
  height: 100%;
  position: relative;
  .login-content {
    width: 100%;
    position: absolute;
    top: 30%;
    transform: translateY(-50%);
  }
  .title {
    font-size: 20px;
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }
  :deep(.van-form) {
    .van-cell-group {
      border-radius: 0;
      padding: 0 10px;
      .van-field {
        border: 1px solid #e1e1e1;
        border-radius: 20px;
        input:-internal-autofill-previewed,
        input:-internal-autofill-selected {
          -webkit-text-fill-color: #2a2d33;
          transition: background-color 5000s ease-out 0.5s;
        }
      }
    }
  }
}
</style>
